package com.zgx.plus.system.controller.system;

import com.zgx.plus.common.aop.Log;
import com.zgx.plus.common.base.BaseController;
import com.zgx.plus.common.enums.BusinessType;
import com.zgx.plus.common.exception.BizException;
import com.zgx.plus.common.response.R;
import com.zgx.plus.common.response.page.TableDataInfo;
import com.zgx.plus.common.utils.SecurityUtils;
import com.zgx.plus.system.api.dto.SysDeptDto;
import com.zgx.plus.system.api.dto.SysUserDto;
import com.zgx.plus.system.api.pos.SysRole;
import com.zgx.plus.system.api.pos.SysUser;
import com.zgx.plus.system.api.vos.SysRoleVo;
import com.zgx.plus.system.api.vos.SysUserVo;
import com.zgx.plus.system.api.vos.TreeSelect;
import com.zgx.plus.system.service.SysDeptService;
import com.zgx.plus.system.service.SysRoleService;
import com.zgx.plus.system.service.SysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysDeptService deptService;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUserDto user) {
        startPage();
        return getDataTable(userService.selectUserList(user));
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
//  List<SysUser> list = userService.selectUserList(user);
//  ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//  util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public R<String> importData(MultipartFile file, boolean updateSupport) throws Exception {
//  ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//  List<SysUser> userList = util.importExcel(file.getInputStream());
//  String operName = getUsername();
//  String message = userService.importUser(userList, updateSupport, operName);
        return R.ok();
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
//  ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//  util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public R<Map<String, Object>> getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        try {
            Map<String, Object> ajax = new HashMap<>();
            List<SysRoleVo> roles = roleService.selectRoleAll();
            ajax.put("roles", SysUserVo.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
//   ajax.put("posts", postService.selectPostAll());//todo
            if (Objects.nonNull(userId)) {
                SysUserVo sysUser = userService.selectUserById(userId);
                ajax.put("data", sysUser);
//    ajax.put("postIds", postService.selectPostListByUserId(userId));//todo
                ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
            }
            return R.ok(ajax);
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("获取用户详情失败：{0}", e.getMessage()));
        }
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody SysUserVo user) {
        try {
            user.setCreateBy(getUsername());
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            return R.ok(userService.insertUser(user));
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("新增用户{0}失败：{1}", user.getUserName(), e.getMessage()));
        }
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody SysUserVo user) {
        try {
            user.setUpdateBy(getUsername());
            return R.ok(userService.updateUser(user));
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("新增用户{0}失败：{1}", user.getUserName(), e.getMessage()));
        }
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public R remove(@PathVariable Long[] userIds) {
        try {
            if (ArrayUtils.contains(userIds, getUserId())) {
                return R.fail("当前用户不能删除");
            }
            return R.ok(userService.deleteUserByIds(userIds));
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("删除用户{0}失败：{1}", userIds, e.getMessage()));
        }
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public R resetPwd(@RequestBody SysUserVo user) {
        try {
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            user.setUpdateBy(getUsername());
            return R.ok(userService.resetPwd(user));
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("用户ID：{0}重置密码失败：{1}", user.getUserId(), e.getMessage()));
        }
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public R changeStatus(@RequestBody SysUser user) {
        try {
            user.setUpdateBy(getUsername());
            return R.ok(userService.updateUserStatus(user));
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("用户ID{0}重置密码失败：{1}", user.getUserId(), e.getMessage()));
        }
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public R<Map<String, Object>> authRole(@PathVariable("userId") Long userId) {
        try {
            Map<String, Object> ajax = new HashMap<>();
            ajax.put("user", userService.selectUserById(userId));
            return R.ok(ajax);
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("用户ID{0}获取授权角色失败：{1}", userId, e.getMessage()));
        }
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public R insertAuthRole(Long userId, Long[] roleIds) {
        try {
            return R.ok(userService.insertUserAuth(userId, roleIds));
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("用户ID{0}授权角色失败：{1}", userId, e.getMessage()));
        }
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public R<List<TreeSelect>> deptTree(SysDeptDto dept) {
        try {
            return R.ok(deptService.selectDeptTreeList(dept));
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("获取部门树列表失败：{0}", e.getMessage()));
        }
    }
}
